;<script setup lang="ts">
import { request } from '@/api';
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
// 把 base64 转换成 blob 二进制数据对象
import base64ToBlob from 'b64-to-blob'

//是否显示动作面板（半模态弹窗）
const showAvatarSheet = ref(false)

//菜单文字
const actions = [{ name: '相册' }, { name: '拍照' }]

// date-picker 组件的日期格式为数组 ['YYYY','MM','DD']
const birthday=ref(['','',''])

//选择菜单时触发
const onSelectAvatar = async  (item: ActionSheetAction, index: number) => { 
  console.log('选择菜单时触发-onSelectAvatar', item, index)
  let datastr = ''
  if (item.name === '相册') {
    datastr = await mk.pickerPhoto()
    onUpdateAvatar(datastr)
  } else if (item.name === '拍照') {
    datastr = await mk.pickerCamera()
    onUpdateAvatar(datastr)
  }
   console.log('图片数据',datastr)
}

// 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    // 关闭动作面板，提示上传
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    
    // 把 base64 字符串转换
    const image = base64ToBlob(data, 'image/jpeg')
    // 后端要求传递 FormData 数据
    const fd = new FormData()
    // 按文档要求准备参数
    fd.append('file', image, Date.now() + '.jpeg')
    
    // 前端上传文件用 post 请求即可
    const res = await request.post<MkResponse<{ avatar: string }>>(
      'member/profile/avatar',
      fd,
    )
    console.log('上传头像成功', res.data)
    
    // 更新表单的数据
    profile.value.avatar = res.data.result.avatar
    // 查询原生鸿蒙的用户信息
    const user = mk.queryUser()
    // 更新原生鸿蒙的用户信息
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    // 成功弹窗提示
    showToast({ message: '上传成功' })
    
  } catch {
    // 失败弹窗提示
    showToast({ message: '上传失败' })
  }
}

//是否显示生日日期选择（半模态弹窗）
const showBirthdayPopup = ref(false)

const onChangeBirthday = (date: { selectedValues: string[] }) => {
  console.log('选择生日时触发-onChangeBirthday', date)
  showBirthdayPopup.value = false
  // 把 selectedValues 转换成字符串，用于后端表单提交
  profile.value.birthday=date.selectedValues.join('-')
}

//是否显示地址选择（半模态弹窗）
const showLocationPopup = ref(false)
const areaColumns = ref<AreaColumns>()
onMounted(async () => {
  const data = await mk.getAreaColumns()
  areaColumns.value = data
  console.log('获取地址数据', data)
})

const onSelectedLocation = (data: { selectedValues: string[],selectedOptions: { text: string }[] }) => {
  showLocationPopup.value = false
  console.log('选择地址时触发-onSelectedLocation', data);
  // 后端：表单提交时要求的是 省市区的 编码
  profile.value.provinceCode = data.selectedValues[0] 
  profile.value.cityCode = data.selectedValues[1] 
  profile.value.countyCode = data.selectedValues[2]
  // 前端：界面展示是 省市区的 文本拼接
  profile.value.fullLocation = data.selectedOptions.map(item => item.text).join(' ')
}

const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]

const showProfessionPopup = ref(false)

const onChangeProfession = (data: { selectedValues: string[] }) => {
  console.log('选择职业时触发-onChangeProfession', data.selectedValues);
  profile.value.profession=data.selectedValues[0]
  showProfessionPopup.value = false
}

const profile = ref<ProfileInfo>({}as ProfileInfo)

onMounted(async () => {
  showLoadingToast({message: '加载中...',duration:0,forbidClick:true})
  const data = await request.get<MkResponse<ProfileInfo>>('/member/profile')
  console.log('获取个人资料', data)
  profile.value = data.data.result
   // 后端数据格式与前端组件格式不一致，需要按组件要求转换数据格式
  // 转换保存生日数据，按 date-picker 要求准备默认值展示
  birthday.value=profile.value.birthday.split('-')
  closeToast()
})

const loading = ref(false)

const onSubmit = async () => {
  //按钮的加载状态
  loading.value = true
   const res = await request.put<MkResponse<ProfileInfo>>(
    '/member/profile',
    profile.value,
  )
  //关闭按钮的加载状态
  loading.value = false
  console.log('修改个人资料', res.data)
  //更新原生鸿蒙应用的用户头像和昵称
  const userInfo = mk.queryUser()
  userInfo.nickname = profile.value.nickname
  userInfo.avatar = profile.value.avatar
  mk.updateUser(userInfo)
  //成功提示
  showToast({ message: res.data.msg })
}

</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image 
      @click="showAvatarSheet = true" 
      round 
      width="100" 
      height="100" 
      class="avatar-img"
      :src=profile.avatar
        >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    
     <!-- 动作面板组件，类似鸿蒙的半模态弹窗 -->
   <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="actions"
      @select="onSelectAvatar"
      cancel-text="取消"
      close-on-click-action
      :style="{ paddingBottom: '20px' }"
    />

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell  title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field v-model="profile.birthday" @click="showBirthdayPopup = true" label="生日" readonly placeholder="请选择日期"></van-field>
      <van-field v-model="profile.fullLocation" @click="showLocationPopup = true" label="所在地" readonly placeholder="请选择所在地"></van-field>
      <van-field v-model="profile.profession" @click="showProfessionPopup = true" label="职业" readonly placeholder="请选择职业"></van-field>
    </van-cell-group>
    <p>{{profile}}</p>

    <div class="submit">
      <van-button round block type="primary" @click="onSubmit" :loading="loading"  :disabled="loading">
        保存资料
      </van-button>
    </div>

    
<!-- 弹层，带圆角，位置为底部 -->
<van-popup v-model:show="showBirthdayPopup" round position="bottom">
  <!-- 日期选择器 -->
  <van-date-picker 
  v-model="birthday"
  title="选择日期" 
  @cancel="showBirthdayPopup = false" 
  @confirm="onChangeBirthday"
  :min-date="new Date('1980-01-01')"
  :max-date="new Date()"
  />
</van-popup>

<!-- 选择所在地弹层 -->
<van-popup v-model:show="showLocationPopup" round position="bottom">
  <van-area  @cancel="showLocationPopup = false" :area-list="areaColumns " @confirm="onSelectedLocation"></van-area>
</van-popup>


<!-- 打开选择职业弹层 -->
<van-popup v-model:show="showProfessionPopup" round position="bottom">
  <van-picker title="选择职业" :columns="columns" @confirm="onChangeProfession" @cancel="showProfessionPopup = false" />
</van-popup>
</div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>